﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using System.Data;
using LDSP.Util;
using BYFW.BOL;
using System.IO;
using LDSP.Helper;

namespace LDSP.UI.EnterpriseAdmin
{
    public partial class MngCatalog : LDSP.BRL.BaseEnterpriseAdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.InitData();
                        this.BindTree();
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected TreeNode m_selectedNode = null;
        protected Catalog m_catalog = null;
        protected Catalog m_parentCatalog = null;

        protected int ParentID
        {
            get { return this.GetVSInt("ParentID"); }
            set
            {
                this.SetVS("ParentID", value);
                m_parentCatalog = null;
            }
        }
        protected int LastID
        {
            get { return this.GetVSInt("LastID"); }
            set
            {
                this.SetVS("LastID", value);
                m_catalog = null;
            }
        }
        protected Catalog Catalog
        {
            get
            {
                if (m_catalog == null)
                {
                    m_catalog = new Catalog();
                    if (LastID != 0)
                    {
                        m_catalog.GetProperties(LastID);
                    }
                }
                return m_catalog;
            }
        }

        protected Catalog ParentCatalog
        {
            get
            {
                if (m_parentCatalog == null)
                {
                    m_parentCatalog = new Catalog();
                    if (ParentID != 0)
                    {
                        m_parentCatalog.GetProperties(ParentID);
                    }
                }
                return m_parentCatalog;
            }
        }
        protected bool IsAdd
        {
            get { return LastID == 0; }
        }

        protected bool RB()
        {
            return true;
        }
        protected void SetStatus()
        {
            this.lbl_op.Text = IsAdd ? "【添加】" : "【修改】";
            this.lbl_op.Style["color"] = IsAdd ? "red" : "blue";
            this.ClientComfirm(this.btn_ok, string.Format("您确定执行{0}操作吗？", IsAdd ? "添加" : "修改"));

            //如果是默认目录，则不能新增子目录和删除。
            if (Catalog.ID > 0 && Catalog.EnterpriseID == 0)
            {
                this.btn_add.Enabled = false;
                this.btn_delete.Enabled = false;
                this.btn_ok.Enabled = false;
            }
            else
            {
                this.btn_add.Enabled = true;
                this.btn_delete.Enabled = true;
                this.btn_ok.Enabled = true;
            }
        }
        protected void InitData()
        {
            this.LastID = 0;
            this.InitDataSelect();
        }
        protected void InitDataSelect()
        {
            this.txt_name.Text = Catalog.Name;
            this.txt_comment.Text = Catalog.Comment;
            this.lbl_parentCatalog.Text = IsAdd ? ParentCatalog.Name : Catalog.Parent.Name;
            this.SetStatus();
        }
        protected void ValidateDataBefore()
        {
            if ((ParentCatalog.ID != 0 && ParentCatalog.EnterpriseID == 0) ||
                (!IsAdd && Catalog.EnterpriseID == 0))
            {
                throw new CustomException("默认栏目不允许操作！");
            }
        }
        protected void ValidateDataAfter()
        {
            if (Catalog.Name == "")
            {
                throw new BYFW.BOL.CustomException("名称不能为空！");
            }
        }
        protected void SetData()
        {
            this.ValidateDataBefore();
            Catalog.Name = this.txt_name.Text.Trim();
            Catalog.Comment = this.txt_comment.Text;
            if (IsAdd)
            {
                Catalog.ParentID = ParentID;
                Catalog.EnterpriseID = LoginUser.EnterpriseID;
            }
            this.ValidateDataAfter();
        }
        protected void Add()
        {
            this.SetData();
            Catalog.Add();
            AddEnterpriseCatalog();
            this.InsertNode();
            this.LastID = 0;
            this.JSAlert("添加成功！");
        }

        private void AddEnterpriseCatalog()
        {
            R_EnterpriseCatalog m_enterprise_catalog = new R_EnterpriseCatalog();
            m_enterprise_catalog.CatalogID = Catalog.ID;
            m_enterprise_catalog.EnterpriseID = this.LoginUser.EnterpriseID;
            m_enterprise_catalog.Add();
        }
        protected void Update()
        {
            this.SetData();
            Catalog.Update();
            this.UpdateNode();
            this.JSAlert("更新成功！");
        }
        protected void InitDataDynamicBefore()
        {
            if (tre_obj.SelectedNode != null)
            {
                m_selectedNode = tre_obj.SelectedNode;
                tre_obj.SelectedNode.Selected = false;
            }
        }

        protected void BindTree()
        {
            this.tre_obj.Nodes.Clear();
            List<Catalog> rootCatalogs = new Catalog().GetListRootByDefault();
            //获取企业自定义的目录
            rootCatalogs.AddRange(new Catalog().GetListRootByEnterpriseID(LoginUser.EnterpriseID));
            rootCatalogs = SortCatalogList(rootCatalogs);
            for (int i = 0; i < rootCatalogs.Count; i++)
            {
                TreeNode nd = new TreeNode();
                nd.Text = rootCatalogs[i].Name;
                nd.Value = rootCatalogs[i].ID.ToString();
                this.tre_obj.Nodes.Add(nd);
                if (rootCatalogs[i].ID == ParentID)
                {
                    nd.Select();
                    Expand(nd);
                }
                this.BindTreeAssis(nd, rootCatalogs[i].ID);
                nd.CollapseAll();
            }
        }
        protected void BindTreeAssis(TreeNode parent, int parentID)
        {
            List<Catalog> catalogs = new Catalog().GetListByParentID(parentID);
            catalogs = SortCatalogList(catalogs);
            for (int i = 0; i < catalogs.Count; i++)
            {
                TreeNode nd = new TreeNode();
                nd.Text = catalogs[i].Name;
                nd.Value = catalogs[i].ID.ToString();
                parent.ChildNodes.Add(nd);
                if (catalogs[i].ID == ParentID)
                {
                    nd.Select();
                    Expand(nd);
                }
                this.BindTreeAssis(nd, catalogs[i].ID);
            }
        }
        protected void Expand(TreeNode node)
        {
            if (node.Parent != null)
            {
                node.Parent.Expand();
                Expand(node.Parent);
            }
        }
        protected void SelectNode()
        {
            if (m_selectedNode != null)
            {
                m_selectedNode.Selected = true;
            }
        }
        protected void InsertNode()
        {
            TreeNode nd = new TreeNode();
            nd.Text = Catalog.Name;
            nd.Value = Catalog.ID.ToString();
            if (ParentID == 0)
            {
                this.tre_obj.Nodes.Add(nd);
            }
            else
            {
                if (m_selectedNode != null)
                {
                    m_selectedNode.ChildNodes.Add(nd);
                    this.Expand(nd);
                }
                else
                {
                    this.BindTree();
                }
            }
            this.SaveSequence(this.tre_obj.Nodes);
        }
        protected void UpdateNode()
        {
            if (m_selectedNode != null)
            {
                m_selectedNode.Text = Catalog.Name;
                this.Expand(m_selectedNode);
            }
            else
            {
                this.BindTree();
            }
        }
        protected void DeleteNode(TreeNode nd)
        {
            if (nd != null)
            {
                if (nd.Parent == null)
                {
                    tre_obj.Nodes.Remove(nd);
                }
                else
                {
                    nd.Parent.ChildNodes.Remove(nd);
                }
            }
        }

        protected void GetCheckedNodes(List<TreeNode> checkedNodes, TreeNodeCollection children)
        {
            for (int i = 0; i < children.Count; i++)
            {
                if (children[i].Checked)
                {
                    checkedNodes.Add(children[i]);
                }
                GetCheckedNodes(checkedNodes, children[i].ChildNodes);
            }
        }

        protected void btn_add_Click(object sender, EventArgs e)
        {
            try
            {
                this.InitData();
                this.SelectNode();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_addRoot_Click(object sender, EventArgs e)
        {
            try
            {
                this.ParentID = 0;
                this.InitData();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                this.ValidateConCurrent();
                if (IsAdd)
                {
                    this.Add();
                }
                else
                {
                    this.Update();
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
            finally
            {
                this.InitDataSelect();
                this.SelectNode();
            }
        }
        protected void btn_delete_Click(object sender, EventArgs e)
        {
            try
            {
                List<TreeNode> checkedNodes = new List<TreeNode>();
                this.GetCheckedNodes(checkedNodes, this.tre_obj.Nodes);
                for (int i = 0; i < checkedNodes.Count; i++)
                {
                    Catalog ett = new BRL.Catalog();

                    ett.GetProperties(this.GetInt(checkedNodes[i].Value));

                    if (ett.EnterpriseID > 0)
                    {
                        if (LastID == ett.ID)
                        {
                            ParentID = 0;
                            this.InitData();
                        }

                        //删除t_r_enterprise_catalog关系.
                        new R_EnterpriseCatalog().DeleteByEnterpriseAndCatalog(null, ett.EnterpriseID, ett.ID);

                        ett.Delete();
                        this.DeleteNode(checkedNodes[i]);
                    }
                }
                this.SelectNode();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void tre_obj_SelectedNodeChanged(object sender, EventArgs e)
        {
            try
            {
                this.ValidateConCurrent();
                ParentID = this.GetInt(this.tre_obj.SelectedValue);
                LastID = ParentID;
                this.InitDataSelect();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void btn_exportAll_Click(object sender, EventArgs e)
        {
            IList<R_EnterpriseCatalog> allowedCatalog = new List<R_EnterpriseCatalog>();
            foreach (R_EnterpriseCatalog cod in EnterpriseUserCatalogs)
            {
                allowedCatalog.Add(cod);
            }

            //获取模板
            string template = string.Empty;
            string path = Server.MapPath("~\\Templates\\UserSpecified\\FavoriteCodification\\" + this.LoginUser.EnterpriseID + ".xls");
            template = File.Exists(path) ? path : "FavorateCodification.xls";

            FavoriteCodificationExport export = new FavoriteCodificationExport(LoginUser.EnterpriseID, Server, template);

            IDictionary<string, DataTable> tables = export.GetDataTables(allowedCatalog);
            export.Export(tables, Server, template);
        }
        protected void btn_exportSelected_Click(object sender, EventArgs e)
        {
            //获取模板
            string template = string.Empty;
            string path = Server.MapPath("~\\Templates\\UserSpecified\\FavoriteCodification\\" + this.LoginUser.EnterpriseID + ".xls");
            template = File.Exists(path) ? path : "FavorateCodification.xls";
            FavoriteCodificationExport export = new FavoriteCodificationExport(LoginUser.EnterpriseID, Server, template);

            IList<Catalog> catalogs = GetSelectedCatalogs();
            IList<R_EnterpriseCatalog> catas = new List<R_EnterpriseCatalog>();

            //获取catalog列表
            foreach (R_EnterpriseCatalog c in EnterpriseUserCatalogs)
            {
                foreach (Catalog ct in catalogs)
                {
                    if (c.Catalog.ID == ct.ID)
                    {
                        catas.Add(c);
                        break;
                    }
                }
            }

            IDictionary<string, DataTable> tables = export.GetDataTables(catas);
            export.Export(tables, Server, template);
        }
        protected void btn_moveUp_Click(object sender, EventArgs e)
        {
            try
            {
                int selectedIndex = UIHelper.GetIndexForSelectedNode(this.tre_obj, m_selectedNode);
                if (selectedIndex != -1 && selectedIndex != 0)
                {
                    TreeNodeCollection nodes = m_selectedNode.Parent == null ? this.tre_obj.Nodes : m_selectedNode.Parent.ChildNodes;
                    TreeNode nextNode = nodes[selectedIndex - 1];
                    Catalog selectedCatalog = this.GetCataLog(m_selectedNode);
                    Catalog nextCatalog = this.GetCataLog(nextNode);
                    nodes.RemoveAt(selectedIndex - 1);
                    nodes.AddAt(selectedIndex, nextNode);
                }
                this.SelectNode();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_moveDown_Click(object sender, EventArgs e)
        {
            try
            {
                int selectedIndex = UIHelper.GetIndexForSelectedNode(this.tre_obj, m_selectedNode);
                if (selectedIndex != -1)
                {
                    TreeNodeCollection nodes = m_selectedNode.Parent == null ? this.tre_obj.Nodes : m_selectedNode.Parent.ChildNodes;
                    if (selectedIndex != nodes.Count - 1)
                    {
                        TreeNode nextNode = nodes[selectedIndex + 1];
                        Catalog selectedCatalog = this.GetCataLog(m_selectedNode);
                        Catalog nextCatalog = this.GetCataLog(nextNode);
                        nodes.RemoveAt(selectedIndex + 1);
                        nodes.AddAt(selectedIndex, nextNode);
                    }
                }
                this.SelectNode();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_saveSequence_Click(object sender, EventArgs e)
        {
            try
            {
                this.SaveSequence(this.tre_obj.Nodes);
                this.JSAlert("栏目顺序保存成功！");
            }
            catch { }
        }

        private void SaveSequence(TreeNodeCollection nodes)
        {
            for (int i = 0; i < nodes.Count; i++)
            {
                var catalog = this.GetCataLog(nodes[i]);
                var ec = this.GetEnterpriseCatalogForLoginUserByCatalogID(catalog.ID);
                ec.Sequence = i;
                ec.Update();
                this.SaveSequence(nodes[i].ChildNodes);
            }
            this.SelectNode();
        }

        private IList<Catalog> GetSelectedCatalogs()
        {
            IList<Catalog> catalogs = new List<Catalog>();
            List<TreeNode> checkedNodes = new List<TreeNode>();
            this.GetCheckedNodes(checkedNodes, this.tre_obj.Nodes);

            foreach (TreeNode node in checkedNodes)
            {
                catalogs.Add(GetCataLog(node));
            }
            return catalogs;
        }
        private Catalog GetCataLog(TreeNode node)
        {
            Catalog ett = new BRL.Catalog();
            ett.GetProperties(this.GetInt(node.Value));

            return ett;
        }

        /// <summary>
        /// 并发操作时，验证数据是否存在
        /// </summary>
        private void ValidateConCurrent()
        {
            if (LastID != Catalog.ID || ParentID != ParentCatalog.ID)
            {
                this.BindTree();
                LastID = 0;
                ParentID = 0;
                throw new CustomException("数据已过期，请在页面刷新后，重新操作！");
            }
        }
    }
}